package org.cnc.explain.db.transaction;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * <p>
 * 
 * </p>
 *
 * @author zhiyong.tan
 * @since 2022-07-25
 */
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = "org.cnc.explain.db.transaction.mapper")
@ComponentScan(basePackages = "org.cnc.explain.db.transaction")
public class TransactionApplicationConfig {
	public static final String DATASOURCE_CONNECTION_STRING = "jdbc:mysql://114.67.81.63:3307/java_std?useUnicode=true&characterEncoding=UTF-8&useSSL=false";
	public static final String DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver";


	@Bean
	public DataSource dataSource() {
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName(DRIVER_CLASS_NAME);
		dataSource.setUrl(DATASOURCE_CONNECTION_STRING);
		dataSource.setUsername("root");
		dataSource.setPassword("admin123");
		return dataSource;
	}

	@Bean
	public DataSourceTransactionManager dataSourceTransactionManager(){
		return new DataSourceTransactionManager(dataSource());
	}

	@Bean
	public SqlSessionFactoryBean sqlSessionFactory() throws IOException {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
		bean.setDataSource(dataSource());
		return bean;
	}
}
